//
// fileint.cpp
// fileint
// File Interface into the Protea Project, requires a file containing XML data for business transactions
// Copyright (C) 2003, 2004, 2005 eXegeSys, Inc.
// Copyright (C) 2008 Bruce A. James
//
// This program is part of the Protea Project.
//
// The Protea Project is free software; you can redistribute it and/or modify it 
// under the terms of the GNU General Public License as published by the 
// Free Software Foundation, either version 3 of the License, or (at your 
// option) any later version.
//
// The Protea Project is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
// 
// You should have received a copy of the GNU General Public License along 
// with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Please send correspondence to:
// 
// theproteaproject@gmail.com
//

#include "../SDK/ToolsInterface.h"

#include <iostream>

using namespace std;

#define MAX_LEN 65535

int main( int argc, char** argv )
{
	Protea::ShowIntro( "fileint" );

	if (argc > 1 && !strcmp(argv[1],"-L"))
	{
		Protea::ShowLicense();
		return 0;
	};

	if ( argc <  3 || argc>4)
	{
		cout << "Usage: fileint <filename> <xmlint listener port> <host>" << endl;
		exit( 1 );
	};

	char* me = new char[ MAX_PATH ];
	if (argc==3) {
		if ( XCGetHostName (me, MAX_PATH) )
		{
			cout << "Could not determine host name." << endl;
			return 1;
		};
	} else
		strcpy( me, argv[3] );

	cout << "Connect to host: " << me << ":" << argv[2] << endl;

	XCSocketTransport connect( NULL );
	connect.Create( AF_INET, SOCK_STREAM, 0 );
	connect.Connect( me, atol( argv[ 2 ] ) );

	// read in file, send to port
	XCFileTransport filename( NULL );
	filename.Open( argv[ 1 ] );

	long length = filename.GetSize();
	char* data = new char[ length + 1 ];
	memset( data, 0, length + 1 );
	filename.Recv( data, length );
	connect.Send( data, length + 1 );
	filename.Close();
	delete[] data;
	delete[] me;

	// wait for replies
	char buf[ MAX_LEN ];
	do {
		length = connect.Recv( &buf, MAX_LEN );
		if ( buf[0] )
		{
			cout << buf << endl;
			if (memchr( buf, 0, length))
				length = -1;
			memset( buf, 0, MAX_LEN );
		};
	} while (length > 0);
	connect.Close();
};
